package com.sokal.easycare.modules.ad.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sokal.easycare.common.persistence.Page;
import com.sokal.easycare.common.service.CrudService;
import com.sokal.easycare.common.utils.StringUtils;
import com.sokal.easycare.modules.ad.entity.AdInfo;
import com.sokal.easycare.modules.ad.dao.AdInfoDao;
import com.sokal.easycare.modules.ad.entity.AdInfoFile;
import com.sokal.easycare.modules.ad.dao.AdInfoFileDao;

/**
 * 广告Service
 * @author liliangdong
 * @version 2017-05-03
 */
@Service
@Transactional(readOnly = true)
public class AdInfoService extends CrudService<AdInfoDao, AdInfo> {

	@Autowired
	private AdInfoFileDao adInfoFileDao;
	
	public AdInfo get(String id) {
		AdInfo adInfo = super.get(id);
		adInfo.setAdInfoFileList(adInfoFileDao.findList(new AdInfoFile(adInfo)));
		return adInfo;
	}
	
	public List<AdInfo> findList(AdInfo adInfo) {
		return super.findList(adInfo);
	}
	
	public Page<AdInfo> findPage(Page<AdInfo> page, AdInfo adInfo) {
		return super.findPage(page, adInfo);
	}
	
	@Transactional(readOnly = false)
	public void save(AdInfo adInfo) {
		super.save(adInfo);
		for (AdInfoFile adInfoFile : adInfo.getAdInfoFileList()){
			if (adInfoFile.getId() == null){
				continue;
			}
			if (AdInfoFile.DEL_FLAG_NORMAL.equals(adInfoFile.getDelFlag())){
				if (StringUtils.isBlank(adInfoFile.getId())){
					adInfoFile.setAdInfo(adInfo);
					adInfoFile.preInsert();
					adInfoFileDao.insert(adInfoFile);
				}else{
					adInfoFile.preUpdate();
					adInfoFileDao.update(adInfoFile);
				}
			}else{
				adInfoFileDao.delete(adInfoFile);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(AdInfo adInfo) {
		super.delete(adInfo);
		adInfoFileDao.delete(new AdInfoFile(adInfo));
	}
	
}